package com.huluspace.authsecurity.security;

import org.springframework.context.annotation.*;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.authentication.configuration.*;
import org.springframework.security.config.annotation.web.builders.*;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.*;
import org.springframework.security.web.*;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

// 标记为配置类，Spring启动时会扫描并加载它
@Configuration
public class SecurityConfig {

  /**
   * 核心安全过滤链配置
   */
  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http, JwtFilter jwtFilter) throws Exception {
    return http
        .csrf(AbstractHttpConfigurer::disable) // 禁用CSRF跨站请求伪造防护
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/auth.html", "/login").permitAll() // 允许匿名访问的请求路径
            .requestMatchers("/hello").hasRole("ADMIN") // 配置需要ADMIN角色的访问路径
            .anyRequest().authenticated() // 所有其他请求都必须已认证
        ) // 请求路径的访问控制配置
        // 设置会话（Session）创建策略为无状态，符合JWT的认证方式
        .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class) // 将jwtFilter插入过滤器链，确保它在默认登录认证逻辑之前执行
        .build(); // 构建整个过滤链并返回，Spring自动使用它
  }

  @Bean
  public AuthenticationManager authManager(AuthenticationConfiguration config) throws Exception {
    return config.getAuthenticationManager();
  }
}

